package com.yunzai.file.filter;

import com.yunzai.file.config.FileDownloadConfig;
import com.yunzai.file.config.FileUploadConfig;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

//@Component
public class FileDownloadFilter
//        extends OncePerRequestFilter
{

//    @Autowired
//    private FileDownloadConfig fileDownloadConfig;
//
//    @Autowired
//    private FileUploadConfig fileUploadConfig;
//
//    /**
//     * @param request
//     * @param response
//     * @param filterChain
//     * @throws ServletException
//     * @throws IOException
//     */
//    @Override
//    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
//        request.setCharacterEncoding("utf-8");
//        String requestURI = request.getRequestURI();
//        String url = fileDownloadConfig.getUrl();
//        url = url.startsWith("/") ? url : "/" + url;
//        url = url.endsWith("/") ? url : url + "/";
//        if (requestURI.contains(url)) {
//            String path = fileUploadConfig.getStorage().getPath();
//            path = path.startsWith("/") ? path : "/" + path;
//            path = path.endsWith("/") ? path : path + "/";
//            String filename = requestURI.substring(url.length(), requestURI.length());
//            File file = new File(path + filename);
//            if (!file.exists()) {
//                logger.error("文件不存在！");
//            }
//            FileInputStream fileInputStream = null;
//            ServletOutputStream outputStream = null;
//            try {
//                fileInputStream = new FileInputStream(file);
//                outputStream = response.getOutputStream();
//                outputStream.write(fileInputStream.readAllBytes());
//                outputStream.flush();
//            } catch (FileNotFoundException e) {
//                logger.error("文件不存在！");
//            } finally {
//                if (fileInputStream != null) {
//                    fileInputStream.close();
//                }
//                if (outputStream != null) {
//                    outputStream.close();
//                }
//            }
//        }
//        filterChain.doFilter(request, response);
//    }
}
